<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\WxWorkChatData;
use App\Models\WxWorkChatDataPullLog;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class WorkWeChatController extends Controller
{
    protected $msg_save_config = [];
    public function __construct()
    {
        $this->msg_save_config = config('wechat.work.msg_save');
    }

    public function saveMsg(Request  $request)
    {
        $data = $request->all();
        logger('企业微信回调消息', $data);

        $config = config('wechat.work.msg_save');

        $app = Factory::work($config);

        $app->server->push(function($message){
            // $message['FromUserName'] // 消息来源
            // $message['MsgType'] // 消息类型：event ....

            return 'Hello easywechat.';
        });

        $response = $app->server->serve();

        $response->send();
    }

    /**
     * 拉取聊天数据 -- 单次
     * @param int $start_seq 开始拉取的消息序号
     * @param int $limit 每次拉取的条数，最大 1000
     * @param int $total_count 本次要拉取的总条数，够了就停止拉取，0 则不限条数，一直拉取直到全部拉完所有数据才停止
     */
    public function getChatData(int $start_seq = 0, int $limit = 1000, int $total_count = 0)
    {
        $count = 0; // 从 0 开始计数
        while (true) {
            $res = $this->getChatData_once($start_seq, $limit);
            if ($res['code'] != '0' || $res['is_end']) break;

            $start_seq = $res['max_seq'];
            $count += $res['count'];

            if ($total_count > 0 && $count >= $total_count) break;
        }

        dd('拉取结束');
    }

    /**
     * 拉取聊天数据 -- 单次
     * @param int $seq 开始拉取的消息序号
     * @param int $limit 每次拉取条数，最大不能超过 1000条
     * @return array
     */
    public function getChatData_once(int $seq = 0, int $limit = 1000)
    {
        $start = [
            '$seq' => $seq,
            '$limit' => $limit,
        ];
        logger('企业微信 => 拉取聊天数据 => start', $start);

        $config = $this->msg_save_config;
        $corpId = $config['corp_id'];
        $secret = $config['secret'];
        $private_key_file_path = $config['private_key_file_path'];
        $options = [ // 可选参数
            'proxy_host' => '',
            'proxy_password' => '',
            'timeout' => 10, // 默认超时时间为10s
        ];

        try {
            $obj = new \WxworkFinanceSdk($corpId, $secret, $options);

            // 私钥地址
            $privateKey = file_get_contents($private_key_file_path);

            $chats = json_decode($obj->getChatData($seq, $limit), true);
            logger('企业微信 => 拉取聊天数据 => $chats', $chats);

            $count = count($chats['chatdata']);
            if ($count == 0) return ['code' => '0', 'count' => $count, 'is_end' => true];

            $min_seq = $max_seq = 0;
            foreach ($chats['chatdata'] as $key => $val) {
                if ($key == 0) {
                    $min_seq = $max_seq = $val['seq'];
                } else {
                    if ($val['seq'] < $min_seq) $min_seq = $val['seq'];
                    if ($val['seq'] > $max_seq) $max_seq = $val['seq'];
                }

                $decryptRandKey = null;
                openssl_private_decrypt(base64_decode($val['encrypt_random_key']), $decryptRandKey, $privateKey, OPENSSL_PKCS1_PADDING);
                $msg = $obj->decryptData($decryptRandKey, $val['encrypt_chat_msg']);
                $msg = json_decode($msg, true);

//                $obj->downloadMedia($sdkFileId, "/tmp/download/文件新名称.后缀");
                logger('企业微信 => 拉取聊天数据 => $msg => ', $msg);

                WxWorkChatData::query()->create([
                    'seq' => $val['seq'], // 消息的seq值，标识消息的序号
                    'msgid' => $val['msgid'], // 消息id，消息的唯一标识，企业可以使用此字段进行消息去重。
                    'msg' => $msg, // 明文消息，json格式
                    'data' => $val, // 加密数据，json格式，即chatdata里的每一项数据
                ]);
            }

            WxWorkChatDataPullLog::query()->create([
                'min_seq' => $min_seq,
                'max_seq' => $max_seq,
                'count' => $count,
                'res' => $chats,
            ]);

            $is_end = false;
            if ($count < $limit) $is_end = true;
            return ['code' => '0', 'max_seq' => $max_seq, 'count' => $count, 'is_end' => $is_end];

        }catch(\WxworkFinanceSdkException $e) {
            $error = [
                'error_essage' => $e->getMessage(),
                'error_code' => $e->getCode(),
            ];
            logger('企业微信 => 拉取聊天数据 => WxworkFinanceSdkException $error => ', $error);
            return ['code' => '1', 'error' => $error];
        }
    }
}
